package com.ktg.mes.unit.tableVersion.domain;

import com.baomidou.mybatisplus.annotation.*;
import lombok.Data;
import lombok.experimental.Accessors;
import com.ktg.common.annotation.Excel;
import com.ktg.common.core.domain.BaseEntity;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.List;


/**
 * 版本记录对象 zjm_table_model
 *
 * @author byteco
 * @date 2022-12-13
 */

@Data
@Accessors(chain = true)
@TableName("zjm_table_model")
public class ZjmTableModel extends BaseEntity
{
    private static final long serialVersionUID = 1L;

    /** 记录ID */
    @TableId(value = "record_id", type = IdType.AUTO)
    private Long recordId;


    /** 表名 */
    @Excel(name = "表名")
    private String tableName;


    /** 表版本 */
    @Excel(name = "表版本")
    private String tableVersion;


    /** 提示信息 */
    @Excel(name = "提示信息")
    private String message;

    /**
     * 表説明
     */
    @TableField(exist = false)
    private String tableDes;

    /**
     * 类
     */
    @TableField(exist = false)
    private Class<?> aClass;

    List<ZimTableColunm> zjmTableColunmList = new ArrayList<>();



    public ZjmTableModel(Class<?> aClass,String tableVersion,String tableDes){
        this.aClass = aClass;
        this.tableVersion = tableVersion;
        this.tableDes = tableDes;
        updateOrCreateTable(aClass);
    }

    //获取当前能够操作的属性，从新设置model,同时整理能够操作的属性
    public String updateOrCreateTable(Class<?> aClass)  {
        Field[] fieldList = aClass.getDeclaredFields();
        try {

            for (int i = 0;i < fieldList.length;i++){
                ZimTableColunm tableColunm = new ZimTableColunm();
                tableColunm.tableName = tableName;
                Field field = fieldList[i];
                if (Modifier.isFinal(field.getModifiers())){
                    continue;
                }
                TableField tableField = field.getAnnotation(TableField.class);
                if (tableField != null && tableField.exist() == false) {
                    continue;
                }

                String tableFieldName = "";
                if (tableField != null && tableField.value() != null){
                    tableFieldName = tableField.value();
                }else {
                    tableFieldName = camelToUnderline(field.getName());
                }

                tableColunm.columnName = tableFieldName;

                //判断是否同一个数据库
                ZjmTable dsTableField = field.getAnnotation(ZjmTable.class);
                if (dsTableField != null){
                    tableColunm.commentStr = dsTableField.colunmComment();
                    tableColunm.typeStr = dsTableField.colunmType();
                    tableColunm.version = dsTableField.colunmVersion();
                }else {
                    tableColunm.commentStr = "";
                    tableColunm.typeStr = "varchar(255)";
                }
                zjmTableColunmList.add(tableColunm);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 将驼峰命名转化成下划线
     * @param para
     * @return
     */
    public static String camelToUnderline(String para){
        if(para.length()<3){
            return para.toLowerCase();
        }
        StringBuilder sb=new StringBuilder(para);
        int temp=0;//定位
        //从第三个字符开始 避免命名不规范
        for(int i=2;i<para.length();i++){
            if(Character.isUpperCase(para.charAt(i))){
                sb.insert(i+temp, "_");
                temp+=1;
            }
        }
        return sb.toString().toLowerCase();
    }

    //使用说明，需要创建创建基础表的存储过程
    /*

        -- 创建创建基础表的存储过程
        DROP PROCEDURE if EXISTS createTable;
        CREATE PROCEDURE createTable(in tableName VARCHAR(255),in tableDes varchar(255))
        BEGIN
            set @tName := tableName;
            if POSITION(' ' in @tName) = 0 then
                set @sqlName := CONCAT("CREATE TABLE if NOT EXISTS ",@tName," (
                        `id` bigint NOT NULL AUTO_INCREMENT COMMENT 'id',
                        `remark` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '备注',
                        `create_by` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '创建人',
                        `create_time` datetime NULL DEFAULT NULL COMMENT '创建时间',
                        `update_by` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '修改人',
                        `update_time` datetime NULL DEFAULT NULL COMMENT '修改时间',
                        PRIMARY KEY (`id`) USING BTREE
                    ) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '",tableDes,"' ROW_FORMAT = Dynamic;");
                PREPARE STMT FROM @sqlName;
                EXECUTE STMT;
                SELECT 1;
            end if;
        END;
    */


    // 添加数据库字段
    /*

        DROP PROCEDURE if EXISTS alertColum;
        CREATE PROCEDURE alertColum(in tableName VARCHAR(255),in columnName VARCHAR(255),in typeStr VARCHAR(255),in defaultStr VARCHAR(255),in desStr VARCHAR(255))
        BEGIN
            if EXISTS (select * from information_schema.columns where TABLE_SCHEMA = 'mes_text' and table_name = tableName and column_name = columnName)
            then
            SELECT 2;
            set @sqlStr := CONCAT("ALTER TABLE `",tableName,"` MODIFY COLUMN `",columnName,"` ",typeStr," DEFAULT ",defaultStr," COMMENT '",desStr,"'");
            PREPARE STMT FROM @sqlStr;
            EXECUTE STMT;

            ELSE
            SELECT 1;
            set @sqlStr := CONCAT("ALTER TABLE `",tableName,"` ADD COLUMN `",columnName,"` ",typeStr," DEFAULT ",defaultStr," COMMENT '",desStr,"'");
            PREPARE STMT FROM @sqlStr;
            EXECUTE STMT;


            END if;
        -- 	PREPARE STMT FROM @sqlStr;
        END;

        CALL alertColum('demo','name2','VARCHAR(255)','0','测试名称2');

    * */

    /*

    DROP PROCEDURE if EXISTS alertColum;
CREATE PROCEDURE alertColum(in tableName VARCHAR(255),in oldColumnName VARCHAR(255),in columnName VARCHAR(255),in typeStr VARCHAR(255),in defaultStr VARCHAR(255),in desStr VARCHAR(255))
BEGIN
		if EXISTS (select * from information_schema.columns where TABLE_SCHEMA = 'mes_text' and table_name = tableName and column_name = columnName)
	then

	ELSEIF EXISTS (select * from information_schema.columns where TABLE_SCHEMA = 'mes_text' and table_name = tableName and column_name = columnName)
	then
	SELECT 2;
	set @sqlStr := CONCAT("ALTER TABLE `",tableName,"` MODIFY COLUMN `",columnName,"` ",typeStr," DEFAULT ",defaultStr," COMMENT '",desStr,"'");
	PREPARE STMT FROM @sqlStr;
	EXECUTE STMT;

	ELSE
	SELECT 1;
	set @sqlStr := CONCAT("ALTER TABLE `",tableName,"` ADD COLUMN `",columnName,"` ",typeStr," DEFAULT ",defaultStr," COMMENT '",desStr,"'");
	PREPARE STMT FROM @sqlStr;
	EXECUTE STMT;


	END if;
-- 	PREPARE STMT FROM @sqlStr;
END;

CALL alertColum('demo','0','name2','VARCHAR(255)','0','测试名称2');

    * */

}
